package com.example.ricebibackend.common.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 阿里云短信服务工具类
 * @author ricejson
 */
@Component
public class SmsUtil {
    @Value("${sms.accessKeyId}")
    private String accessKeyId;
    @Value("${sms.accessKeySecret}")
    private String accessKeySecret;
    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 配置 Endpoint
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public SendSmsResponse sendMessage(String phoneNumber, String templateCode, String templateParam) throws Exception {
        // 初始化客户端
        Client client = createClient();
        // 构造请求对象
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("米饭中心")
                .setPhoneNumbers(phoneNumber)
                .setTemplateCode(templateCode)
                .setTemplateParam(templateParam);
        // 获得响应对象
        return client.sendSms(sendSmsRequest);
    }
}
